<?php
/**
 * 蜘蛛监控插件 - 许可证管理后台
 * 作者：Eric
 * 网站：https://zibovip.top
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 数据库表创建
register_activation_hook(__FILE__, 'spider_license_create_tables');

function spider_license_create_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    
    // 许可证表
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $sql_licenses = "CREATE TABLE IF NOT EXISTS {$licenses_table} (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        license_key varchar(255) NOT NULL,
        plan varchar(50) NOT NULL DEFAULT 'basic',
        features longtext,
        max_domains int(11) NOT NULL DEFAULT 1,
        expires_at datetime NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY license_key (license_key),
        KEY plan (plan),
        KEY expires_at (expires_at)
    ) {$charset_collate};";
    
    // 激活记录表
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    $sql_activations = "CREATE TABLE IF NOT EXISTS {$activations_table} (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        license_id bigint(20) NOT NULL,
        domain varchar(255) NOT NULL,
        status varchar(20) NOT NULL DEFAULT 'active',
        ip_address varchar(45),
        user_agent text,
        activated_at datetime DEFAULT CURRENT_TIMESTAMP,
        last_check datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY license_domain (license_id, domain),
        KEY domain (domain),
        KEY activated_at (activated_at),
        FOREIGN KEY (license_id) REFERENCES {$licenses_table}(id) ON DELETE CASCADE
    ) {$charset_collate};";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql_licenses);
    dbDelta($sql_activations);

    // 兼容已存在的旧表：确保新增字段存在
    $columns = $wpdb->get_col("SHOW COLUMNS FROM {$activations_table}", 0);
    if ($columns && !in_array('status', $columns, true)) {
        $wpdb->query("ALTER TABLE {$activations_table} ADD COLUMN status varchar(20) NOT NULL DEFAULT 'active' AFTER domain");
    }
    if ($columns && !in_array('last_check', $columns, true)) {
        $wpdb->query("ALTER TABLE {$activations_table} ADD COLUMN last_check datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER activated_at");
    }
}

// 注册激活钩子
register_activation_hook(__FILE__, 'spider_license_create_tables');

// 添加管理菜单
add_action('admin_menu', function() {
    add_menu_page(
        '许可证管理',
        '许可证管理',
        'read',  // 降低权限要求，任何登录用户都可以访问
        'spider-license-manager',
        'spider_license_manager_page',
        'dashicons-admin-network',
        30
    );
});

/**
 * 许可证管理页面
 */
function spider_license_manager_page() {
    if (!is_user_logged_in()) {
        wp_die('请先登录');
    }
    
    // 无论如何，访问页面即尝试创建/升级数据表（幂等）
    spider_license_create_tables();
    update_option('wp_spider_license_tables_created', true);
    
    // 处理表单提交
    if (isset($_POST['action']) && $_POST['action'] === 'add_license') {
        spider_add_license($_POST);
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'delete_license') {
        spider_delete_license($_POST['license_id']);
    }

    if (isset($_POST['action']) && $_POST['action'] === 'deactivate_all') {
        spider_deactivate_all_activations($_POST['license_id']);
    }

    // 处理单个激活码生成
    // 改为仅支持 POST 生成，彻底避免通过URL触发
    if (isset($_POST['action']) && $_POST['action'] === 'generate_single' && current_user_can('manage_options')) {
        if (!wp_verify_nonce($_POST['_wpnonce'] ?? '', 'spider_generate_single')) {
            echo '<div class="notice notice-error"><p>安全验证失败，未生成激活码</p></div>';
        } else {
            $plan = isset($_POST['plan']) ? sanitize_text_field($_POST['plan']) : 'basic';
            $result = spider_generate_single_license($plan);
            if ($result['success']) {
                // PRG：生成成功后重定向，避免刷新重复提交
                wp_safe_redirect(admin_url('admin.php?page=spider-license-manager&gen=1'));
                exit;
            } else {
                echo '<div class="notice notice-error"><p>生成失败：' . esc_html($result['message']) . '</p></div>';
            }
        }
    }

    // 处理导出
    if (isset($_GET['action']) && $_GET['action'] === 'export' && current_user_can('manage_options')) {
        spider_export_licenses();
        exit;
    }

    // 处理清理过期
    if (isset($_GET['action']) && $_GET['action'] === 'cleanup' && current_user_can('manage_options')) {
        $count = spider_cleanup_expired_licenses();
        echo '<div class="notice notice-success"><p>已清理 ' . $count . ' 个过期许可证</p></div>';
    }
    
    // 检查并创建数据库表
    if (!get_option('wp_spider_license_tables_created')) {
        spider_license_create_tables();
        update_option('wp_spider_license_tables_created', true);
        echo '<div class="notice notice-success"><p>许可证数据库表已自动创建！</p></div>';
    }
    
    // 获取许可证列表
    $licenses = spider_get_all_licenses();
    ?>
    <div class="wrap">
        <h1>蜘蛛监控插件 - 许可证管理</h1>
        
        <div class="card" style="max-width: 800px; margin: 20px 0; padding: 20px;">
            <h2>添加新许可证</h2>
            <form method="post">
                <input type="hidden" name="action" value="add_license">
                <table class="form-table">
                    <tr>
                        <th><label for="license_key">许可证密钥</label></th>
                        <td>
                            <input type="text" name="license_key" id="license_key" class="regular-text" placeholder="留空自动生成">
                            <p class="description">格式：XXXXX-XXXXX-XXXXX-XXXXX-XXXXX</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="plan">套餐类型</label></th>
                        <td>
                            <select name="plan" id="plan" required onchange="updateFeatures()">
                                <?php
                                $plans = spider_get_plan_config();
                                foreach ($plans as $key => $plan): 
                                ?>
                                <option value="<?php echo $key; ?>" data-features='<?php echo json_encode($plan['features']); ?>' data-domains="<?php echo $plan['max_domains']; ?>">
                                    <?php echo $plan['name']; ?> (¥<?php echo $plan['price']; ?>/年)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="max_domains">最大域名数</label></th>
                        <td>
                            <input type="number" name="max_domains" id="max_domains" value="1" min="1" max="100">
                        </td>
                    </tr>
                    <tr>
                        <th><label for="expires_at">到期时间</label></th>
                        <td><input type="date" name="expires_at" id="expires_at" required></td>
                    </tr>
                    <tr>
                        <th><label for="features">功能权限</label></th>
                        <td>
                            <div id="features-container">
                                <?php
                                $features = spider_get_feature_list();
                                foreach ($features as $key => $name): 
                                ?>
                                <label><input type="checkbox" name="features[]" value="<?php echo $key; ?>"> <?php echo $name; ?></label><br>
                                <?php endforeach; ?>
                            </div>
                        </td>
                    </tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary">添加许可证</button>
                    <form id="generate-single-form" method="post" style="display:inline-block;margin-left:8px;">
                        <input type="hidden" name="action" value="generate_single">
                        <input type="hidden" name="_wpnonce" value="<?php echo wp_create_nonce('spider_generate_single'); ?>">
                        <input type="hidden" name="plan" id="generate-plan" value="">
                        <button type="button" class="button" onclick="generateSingle()">生成激活码</button>
                    </form>
                </p>
            </form>
            
            <script>
            function updateFeatures() {
                const planSelect = document.getElementById('plan');
                const selectedOption = planSelect.options[planSelect.selectedIndex];
                const features = JSON.parse(selectedOption.getAttribute('data-features'));
                const maxDomains = selectedOption.getAttribute('data-domains');
                
                document.getElementById('max_domains').value = maxDomains;
                
                const checkboxes = document.querySelectorAll('#features-container input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = features.includes(checkbox.value);
                });
            }
            
            function generateSingle() {
                if (confirm('确定要生成一个新的激活码吗？')) {
                    document.getElementById('generate-plan').value = document.getElementById('plan').value;
                    document.getElementById('generate-single-form').submit();
                }
            }
            
            // 初始化
            updateFeatures();
            </script>
        </div>
        
        <h2>许可证列表</h2>
        <div style="margin-bottom: 20px;">
            <button type="button" class="button" onclick="exportLicenses()">导出许可证</button>
            <button type="button" class="button" onclick="cleanupExpired()">清理过期</button>
        </div>
        <div class="table-responsive">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>许可证密钥</th>
                        <th>套餐类型</th>
                        <th>到期时间</th>
                        <th>状态</th>
                        <th>已使用</th>
                        <th>激活域名</th>
                        <th>最大域名</th>
                        <th>功能权限</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($licenses as $license): ?>
                    <?php 
                        $activations = spider_get_license_activations($license['id']);
                        $features = json_decode($license['features'], true) ?: [];
                        $status = spider_get_license_status($license);
                        $days_left = max(0, ceil((strtotime($license['expires_at']) - time()) / 86400));
                    ?>
                    <tr>
                        <td><?php echo $license['id']; ?></td>
                        <td>
                            <code><?php echo esc_html($license['license_key']); ?></code>
                            <button type="button" class="button button-small" onclick="copyToClipboard('<?php echo esc_js($license['license_key']); ?>')">复制</button>
                        </td>
                        <td><?php echo esc_html($license['plan']); ?></td>
                        <td>
                            <?php echo date('Y-m-d', strtotime($license['expires_at'])); ?>
                            <br><small><?php echo $days_left; ?> 天后到期</small>
                        </td>
                        <td>
                            <?php 
                            $status_colors = [
                                'active' => '#46b450',
                                'expired' => '#dc3232',
                                'suspended' => '#ffb900'
                            ];
                            ?>
                            <span style="color: <?php echo $status_colors[$status] ?? '#666'; ?>;">
                                <?php echo spider_get_status_text($status); ?>
                            </span>
                        </td>
                        <td>
                            <?php $used = !empty($activations); ?>
                            <?php if ($used): ?>
                                <span class="usage-badge used">已使用</span>
                            <?php else: ?>
                                <span class="usage-badge unused">未使用</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!empty($activations)): ?>
                                <?php echo count($activations); ?>
                                <br><a href="#" onclick="showActivatedDomains(<?php echo $license['id']; ?>)">查看详情</a>
                            <?php else: ?>
                                <em>未激活</em>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $license['max_domains']; ?></td>
                        <td>
                            <?php foreach ($features as $feature): ?>
                                <span class="feature-badge"><?php echo esc_html($feature); ?></span>
                            <?php endforeach; ?>
                        </td>
                        <td><?php echo esc_html($license['created_at']); ?></td>
                        <td>
                            <form method="post" style="display: inline;">
                                <input type="hidden" name="action" value="delete_license">
                                <input type="hidden" name="license_id" value="<?php echo $license['id']; ?>">
                                <button type="submit" class="button button-link-delete" onclick="return confirm('确定要删除此许可证吗？')">删除</button>
                            </form>
                            <form method="post" style="display: inline;">
                                <input type="hidden" name="action" value="deactivate_all">
                                <input type="hidden" name="license_id" value="<?php echo $license['id']; ?>">
                                <button type="submit" class="button button-small" onclick="return confirm('确定停用所有激活？')">停用所有</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <script>
            function copyToClipboard(text) {
                navigator.clipboard.writeText(text).then(() => {
                    alert('已复制到剪贴板');
                });
            }
            function showActivatedDomains(licenseId) {
                alert('查看激活域名功能待实现');
            }
            function exportLicenses() {
                window.location.href = '<?php echo admin_url('admin.php?page=spider-license-manager&action=export'); ?>';
            }
            function cleanupExpired() {
                if (confirm('确定要清理所有过期的许可证吗？此操作不可恢复。')) {
                    window.location.href = '<?php echo admin_url('admin.php?page=spider-license-manager&action=cleanup'); ?>';
                }
            }
            </script>
        </div>
        
        <style>
            .feature-badge {
                display: inline-block;
                background: #f0f0f0;
                padding: 2px 8px;
                margin: 2px;
                border-radius: 3px;
                font-size: 12px;
            }
            .table-responsive {
                overflow-x: auto;
            }
            .usage-badge { display:inline-block; padding:2px 6px; border-radius:3px; font-size:12px; }
            .usage-badge.used { background:#e6ffed; color:#0a7f2e; border:1px solid #34c759; }
            .usage-badge.unused { background:#fff7ed; color:#92400e; border:1px solid #f59e0b; }
        </style>
    </div>
    <?php
}

// 加载函数库
require_once(dirname(__FILE__) . '/license-functions.php');

/**
 * 添加许可证
 */
function spider_add_license($data) {
    global $wpdb;
    
    $license_key = sanitize_text_field($data['license_key']);
    $plan = sanitize_text_field($data['plan']);
    $expires_at = sanitize_text_field($data['expires_at']);
    $features = json_encode($data['features'] ?? []);
    $max_domains = intval($data['max_domains'] ?? 1);
    
    // 如果没有提供许可证密钥，使用新的单个生成函数
    if (empty($license_key)) {
        $result = spider_generate_single_license($plan, $expires_at);
        if ($result['success']) {
            echo '<div class="notice notice-success"><p>' . esc_html($result['message']) . ' - 激活码: ' . esc_html($result['license_key']) . '</p></div>';
            return;
        } else {
            echo '<div class="notice notice-error"><p>' . esc_html($result['message']) . '</p></div>';
            return;
        }
    }
    
    // 验证许可证密钥格式
    if (!spider_validate_license_key($license_key)) {
        echo '<div class="notice notice-error"><p>许可证密钥格式无效</p></div>';
        return;
    }
    
    // 检查许可证是否已存在
    $existing = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}spider_licenses WHERE license_key = %s",
        $license_key
    ));
    
    if ($existing > 0) {
        echo '<div class="notice notice-error"><p>许可证密钥已存在</p></div>';
        return;
    }
    
    // 直接存入数据表
    $result = $wpdb->insert(
        $wpdb->prefix . 'spider_licenses',
        [
            'license_key' => $license_key,
            'plan' => $plan,
            'features' => $features,
            'max_domains' => $max_domains,
            'expires_at' => $expires_at,
            'created_at' => current_time('mysql')
        ],
        ['%s', '%s', '%s', '%d', '%s', '%s']
    );
    
    if ($result) {
        echo '<div class="notice notice-success"><p>许可证添加成功并已存入数据表！密钥：' . esc_html($license_key) . '</p></div>';
    } else {
        echo '<div class="notice notice-error"><p>添加许可证失败，无法存入数据表</p></div>';
    }
}

/**
 * 批量生成许可证（已废弃，使用 spider_generate_single_license 代替）
 * @deprecated 服务端限制为一次只能生成一个激活码
 */
function spider_batch_generate_licenses($count, $plan = 'basic', $expires_days = 365) {
    // 强制限制为1个，忽略count参数
    $result = spider_generate_single_license($plan, date('Y-m-d', strtotime("+$expires_days days")));
    
    if ($result['success']) {
        return [$result['license_key']];
    } else {
        return new WP_Error('generation_failed', $result['message']);
    }
}

/**
 * 删除许可证
 */
function spider_delete_license($license_id) {
    global $wpdb;
    
    $wpdb->delete(
        $wpdb->prefix . 'spider_licenses',
        ['id' => $license_id],
        ['%d']
    );
    
    echo '<div class="notice notice-success"><p>许可证删除成功！</p></div>';
}

/**
 * 获取所有许可证
 */
function spider_get_all_licenses() {
    global $wpdb;
    
    return $wpdb->get_results("SELECT * FROM {$wpdb->prefix}spider_licenses ORDER BY id DESC", ARRAY_A);
}

/**
 * 获取许可证激活记录
 */
function spider_get_license_activations($license_id) {
    global $wpdb;
    
    $license = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}spider_licenses WHERE id = {$license_id}", ARRAY_A);
    if (!$license) return [];
    
    return $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}spider_activations WHERE license_key = %s ORDER BY activated_at DESC",
            $license['license_key']
        ),
        ARRAY_A
    );
}

/**
 * 获取激活统计
 */
function spider_get_activation_stats() {
    global $wpdb;
    
    $stats = [
        'total_licenses' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}spider_licenses"),
        'active_licenses' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}spider_licenses WHERE expires_at > NOW()"),
        'total_activations' => $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}spider_activations"),
        'unique_domains' => $wpdb->get_var("SELECT COUNT(DISTINCT domain) FROM {$wpdb->prefix}spider_activations")
    ];
    
    return $stats;
}

// 添加统计小工具
add_action('wp_dashboard_setup', function() {
    wp_add_dashboard_widget('spider_license_stats', '蜘蛛监控许可证统计', 'spider_license_stats_widget');
});

function spider_license_stats_widget() {
    $stats = spider_get_activation_stats();
    ?>
    <ul>
        <li>总许可证数: <strong><?php echo $stats['total_licenses']; ?></strong></li>
        <li>有效许可证: <strong><?php echo $stats['active_licenses']; ?></strong></li>
        <li>总激活数: <strong><?php echo $stats['total_activations']; ?></strong></li>
        <li>独立域名: <strong><?php echo $stats['unique_domains']; ?></strong></li>
    </ul>
    <p><a href="<?php echo admin_url('admin.php?page=spider-license-manager'); ?>" class="button">管理许可证</a></p>
    <?php
}